//
//  LXJUserAccountModel.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/3/29.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

/// 新浪用户信息的模型

/// 用户信息保存路径
let userInfoSavePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")

class LXJUserAccountModel: NSObject, NSCoding {
    
    /*
     ["access_token": 2.00jVrygBIAw5qCe9e651140cgzbs_C,
     "remind_in": 157679999,
     "uid": 1551244323,
     "expires_in": 157679999]
     */
    
    /// 令牌
    var access_token: String?
    
    /// 用户 ID
    var uid: Int64 = 0
    
    /// 令牌到期时间
    var expires_in: Int = 0{
        didSet{
            /// 将时间间隔转换为时间戳对象,当前时间+时间间隔就是临牌到期的时间
            expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    /// 令牌到期时间
    var expiresDate: Date?
    
    /// 用户昵称
    var name: String?
    
    /// 用户头像大图
    var avatar_large: String?
    
    /// KVC 构造函数
    init(dic : [String: Any]) {
        super.init()
        /// 字典转模型
        setValuesForKeys(dic)
    }
    /// 防止运行崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // MARK: 归档 解档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        uid = aDecoder.decodeInt64(forKey: "uid")
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    /// 归档,保存用户数据 对象方法
    func saveUserInfoToDocument() -> Void {
        NSKeyedArchiver.archiveRootObject(self, toFile: userInfoSavePath)
    }
    /// 解档,读取用户数据 类方法
    class func readUserInfoFromDocument() -> LXJUserAccountModel? {
      return NSKeyedUnarchiver.unarchiveObject(withFile: userInfoSavePath) as? LXJUserAccountModel
    }
}

